package servlet;

import dao.UserDao;
import pojo.User;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.Objects;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public RegisterServlet() {
        super();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        HttpSession session = request.getSession();
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("register.jsp");
        RequestDispatcher dispatcher = request.getRequestDispatcher("/YZMCodeServlet");
        UserDao dao = new UserDao();

        String account = request.getParameter("account");
        String password = request.getParameter("password");
        String passwordTwo = request.getParameter("passwordTwo");
        String yzm = request.getParameter("yzm");
        User user = dao.findOne(account);

        if (null == account || null == password || null == passwordTwo || "".equals(account) || "".equals(password) || "".equals(passwordTwo)) {
            session.setAttribute("register", "账号或密码不能为空！");
            requestDispatcher.forward(request, response);
            dispatcher.forward(request, response);
        } else if (!(Objects.equals(session.getAttribute("YZMCode"), yzm))) {
            session.setAttribute("register", "验证码错误！");
            requestDispatcher.forward(request, response);
            dispatcher.forward(request, response);
        } else if (!(Objects.equals(password, passwordTwo))) {
            session.setAttribute("register", "两次输入的密码不一样！");
            requestDispatcher.forward(request, response);
            dispatcher.forward(request, response);
        } else if (user != null) {
            session.setAttribute("register", "用户已存在！");
            requestDispatcher.forward(request, response);
            dispatcher.forward(request, response);
        } else {
            User u = new User(account, password, account, null, 0, null, null);
            int count = dao.insertOne(u);
            if (count > 0) {
                session.setAttribute("user", u);
                request.getRequestDispatcher("registerSuccess.jsp").forward(request, response);
            }

            session.setAttribute("register", "注册失败，请重试！");
            requestDispatcher.forward(request, response);
            dispatcher.forward(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
